package com.focusai.efairy.ui.activity.dev;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.util.Pair;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.view.Menu;
import android.view.MenuItem;

import com.focusai.efairy.R;
import com.focusai.efairy.model.request.GetDevConfigRequest;
import com.focusai.efairy.model.request.PostDevConfigRequest;
import com.focusai.efairy.model.response.DevConfigResponse;
import com.focusai.efairy.network.HttpManager;
import com.focusai.efairy.network.Response;
import com.focusai.efairy.network.exception.NetworkException;
import com.focusai.efairy.ui.adapter.base.BaseRecyclerAdapter;
import com.focusai.efairy.ui.adapter.base.BaseRecyclerViewHolder;
import com.focusai.efairy.ui.adapter.base.RecycleViewDivider;
import com.focusai.efairy.ui.adapter.dev.DevConfigAdapter;
import com.focusai.efairy.ui.adapter.warn.SelectPaireAdapter;
import com.focusai.efairy.ui.base.SwipeBackBaseActivity;
import com.focusai.efairy.utils.PrUtils;
import com.focusai.efairy.utils.ScreenUtil;
import com.mylhyl.crlayout.SwipeRefreshRecyclerView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by luo_guangwen on 2017/10/25.
 */

public class DevConfigureActivity extends SwipeBackBaseActivity {
    public static final String KEY_DEV_ID = "key_dev_id";
    private SwipeRefreshRecyclerView mRefreshRecyclerView;
    private DevConfigAdapter mAdapter;
    private List<DevConfigResponse.DevSetting> mList;
    private long deviceId;
    List<Pair<Integer, String>> typeList;
    private int curSelectPosition = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_list);
        if (getIntent() != null) {
            deviceId = getIntent().getLongExtra(KEY_DEV_ID, 0);
        }
        initView();
        setDefaultValues();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuItem menuItem1 = menu.add(MENU_GROUP_ID, MENU_ITEM_ADD, 0, R.string.save).setTitle(R.string.save);
        MenuItemCompat.setShowAsAction(menuItem1, MenuItemCompat.SHOW_AS_ACTION_ALWAYS);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == MENU_ITEM_ADD) {
            save();
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void initView() {
        mRefreshRecyclerView = findView(R.id.swipe_recyce_view);
    }

    @Override
    protected void setDefaultValues() {
        setCenterTitleName("配置信息");
        mList = new ArrayList<>();
        typeList = new ArrayList<>();
        mRefreshRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mAdapter = new DevConfigAdapter(getContext());
        mRefreshRecyclerView.setAdapter(mAdapter);
        mRefreshRecyclerView.getScrollView().addItemDecoration(new RecycleViewDivider(
                mContext, LinearLayoutManager.VERTICAL, ScreenUtil.dp2pix(1), getResources().getColor(R.color.main_line_gray)));
        mAdapter.refreshData(mList);
        mRefreshRecyclerView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (mList.size() > 0) {
                    mRefreshRecyclerView.setRefreshing(false);
                    return;
                }
                loadData();
            }
        });
        mAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseRecyclerViewHolder holder) {
                curSelectPosition = mRefreshRecyclerView.getScrollView().getChildLayoutPosition(holder.itemView);
                DevConfigResponse.DevSetting devSetting = mList.get(curSelectPosition);
                typeList.clear();
                if (devSetting.localType == 0) {
                    int[] range = PrUtils.getRangeByPt(devSetting.pt);
                    if (range != null && range[1] > 0) {
                        if (range[0] != 0) {
                            typeList.add(new Pair<Integer, String>(0, 0 + PrUtils.getUnitByPt(devSetting.pt)));
                        }
                        String value = "";
                        for (int i = range[0]; i <= range[1]; i++) {
                            if (devSetting.pt == 128) {
                                value = PrUtils.getInJianCeStateByHtv(i);
                            } else if (devSetting.pt == 129) {
                                value = PrUtils.getOutJianCeStateByHtv(i);
                            }else {
                                value = i + PrUtils.getUnitByPt(devSetting.pt);
                            }
                            typeList.add(new Pair<Integer, String>(i, value));

                        }

                    }
                } else if (devSetting.localType == 1) {//心跳
                    for (int i = 30; i <= 240; i++) {
                        typeList.add(new Pair<Integer, String>(i, i + "s"));
                    }
                } else if (devSetting.localType == 2) {//音响模式
                    typeList.add(new Pair<Integer, String>(0, "静音"));
                    typeList.add(new Pair<Integer, String>(1, "正常"));
                }
                openSelecteDialog(devSetting);
            }
        });
        mRefreshRecyclerView.setRefreshing(true);
        loadData();
    }

    @Override
    protected void loadData() {
        HttpManager.getInstance().sendRequest(new GetDevConfigRequest(String.valueOf(deviceId), new Response.Listener<DevConfigResponse>() {
            @Override
            protected void onSuccess(DevConfigResponse response) {
                mRefreshRecyclerView.setRefreshing(false);
                if (response != null && response.efairydevicesetting_thv_list != null) {
                    mList.clear();
                    DevConfigResponse.DevSetting devSetting = new DevConfigResponse.DevSetting();
                    devSetting.localType = 1;
                    devSetting.heartbeat_interval_andio = response.efairydevicesetting_heartbeat_interval;
                    mList.add(devSetting);
                    devSetting = new DevConfigResponse.DevSetting();
                    devSetting.localType = 2;
                    devSetting.heartbeat_interval_andio = response.efairydevicesetting_audio_on;
                    mList.add(devSetting);
                    mList.addAll(response.efairydevicesetting_thv_list);
                    mAdapter.notifyDataSetChanged();
                    mRefreshRecyclerView.setEnabledLoad(false);
                }
            }

            @Override
            protected void onFail(NetworkException exception) {
                mRefreshRecyclerView.setRefreshing(false);
                showToast("获取数据失败");
                doException(exception);
            }
        }));
    }

    private void openSelecteDialog(final DevConfigResponse.DevSetting devSetting) {

        AlertDialog.Builder builder = new AlertDialog.Builder(DevConfigureActivity.this);
        SelectPaireAdapter locationAdapter = new SelectPaireAdapter(typeList);
        builder.setAdapter(locationAdapter, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (devSetting.localType == 0) {
                    devSetting.thv = typeList.get(which).first * PrUtils.getRate2ByPt(devSetting.pt);
                    mAdapter.notifyDataSetChanged();
                } else if (devSetting.localType == 1 || devSetting.localType == 2) {
                    devSetting.heartbeat_interval_andio = typeList.get(which).first;
                    mAdapter.notifyDataSetChanged();
                }
            }
        });
        builder.show();
    }

    private void save() {
        if (mList == null || mList.size() == 0) {
            return;
        }
        PostDevConfigRequest.UploadEntry entry = new PostDevConfigRequest.UploadEntry();
        if (mList.size() > 1) {
            entry.efairydevice_id = deviceId;
            entry.efairydevicesetting_heartbeat_interval = mList.get(0).heartbeat_interval_andio;
            entry.efairydevicesetting_audio_on = mList.get(1).heartbeat_interval_andio;
            entry.efairydevicesetting_thv_list = new ArrayList<>();
            for (int i = 2; i < mList.size(); i++) {
                entry.efairydevicesetting_thv_list.add(mList.get(i));
            }
            showSingleDialog("正在保存配置..");
            HttpManager.getInstance().sendRequest(new PostDevConfigRequest(entry, new Response.Listener<String>() {
                @Override
                protected void onSuccess(String response) {
                    closeSingleDialog();
                    showToast("保存配置成功");
                    setResult(RESULT_OK);
                    finish();
                }

                @Override
                protected void onFail(NetworkException exception) {
                    closeSingleDialog();
                    showToast("保存配置失败");
                    doException(exception);
                }
            }));
        }
    }
}
